import router from '@/router'
import pinia, { useUserStore } from '@/stores'
import { StartProgress, CloseProgress } from './utils/nprogress'
import { getlocalStorage } from './utils/localStorage'
import { Keys } from './utils/localStore_key'
const userStore = useUserStore(pinia)
router.beforeEach(async (to, from) => {
  StartProgress()
  let UserInfos = userStore.UserInfos
  // 判断是否没有登录(token)并且不在登录页
  if (!getlocalStorage(Keys.TOKEN) && to.path !== '/login') {
      return '/login'
  }
  // 登录了 想访问登录页重定向首页
  if (getlocalStorage(Keys.TOKEN)) {
    if (to.path == '/login') return '/'
    // 有用户信息
    if (Object.keys(UserInfos).length !== 0) {
      return true
    } else {
      // 否则获取信息
      try {
        await userStore.getUserInfo()

        return { ...to, replace: true }
      } catch (error) {
        await ElMessageBox.confirm('登录过期请重新登录...', {
          confirmButtonText: '确认',
          type: 'warning',
          showCancelButton:false,
          closeOnClickModal:false,
          showClose:false
        })
        await userStore.logout()
        return '/login'
      }
    }
  }
})

router.afterEach((to, from) => {
       CloseProgress()
})
